package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.User;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class UserDao {
	private DBHelp<User> db=new DBHelp<User>();
	public User findByName(String name){
		String sql="SELECT id,username,`PASSWORD`,imgname FROM t_user where username=?";
		return db.executeQueryForObject(sql, new UserRowMapper(), name);
	}

	public User findById(String id){
		String sql="SELECT id,username,`PASSWORD`,imgname FROM t_user where id = ? ";
		return db.executeQueryForObject(sql, new UserRowMapper(),id);
	}
	public List<User> findAll(){
		String sql="SELECT id,username,`PASSWORD`,imgname FROM t_user";
		return db.executeQueryForList(sql, new UserRowMapper());
	}

	public boolean save(String id,User user) {
		String sql="INSERT INTO t_user(id,username,`PASSWORD`,imgname) VALUES(?,?,?,?)";
		return db.executeSQL(sql, id,user.getUsername(),user.getPassword(),user.getImgname());
	}
	public List<User> findByProjectId(String projectid) {
		String sql="SELECT id,username,`PASSWORD`,imgname FROM t_user WHERE id IN(SELECT t_user_id FROM t_user_project WHERE t_project_id=? )";
		return db.executeQueryForList(sql, new UserRowMapper(), projectid);
	}
	
	
	private class UserRowMapper implements RowMapper<User>{

		public User mapRow(ResultSet rs) throws SQLException {
			User user=new User();
			user.setId(rs.getString("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setImgname(rs.getString("imgname"));
			return user;
		}
		
	}


	public boolean update(String userid, User user) {
		String sql="UPDATE t_user SET id=?,username=?,`password`=?,imgname=? WHERE id=?;";
		return db.executeSQL(sql, userid,user.getUsername(),user.getPassword(),user.getImgname(),userid);
	}
	


	
}
